package com.deyuanyun.pic.pig.service.impl;

import java.math.BigDecimal;
import java.util.*;

import javax.annotation.Resource;

import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.pig.controller.query.QueryTaskPointVO;
import com.deyuanyun.pic.pig.controller.vo.*;
import com.deyuanyun.pic.pig.controller.query.QueryListVO;
import com.deyuanyun.pic.settings.controller.pipe.vo.PipeLocationDTO;
import com.deyuanyun.pic.settings.domain.base.AttachmentExample;
import com.deyuanyun.pic.settings.domain.pipe.PipeSegment;
import com.deyuanyun.pic.settings.domain.util.DomainInitUtil;
import com.deyuanyun.pic.settings.service.pipe.PipeLocationService;
import org.springframework.stereotype.Service;

import com.deyuanyun.pic.pig.mapper.PigTaskMapper;
import com.deyuanyun.pic.pig.mapper.PigTaskPointMapper;
import com.deyuanyun.pic.pig.service.CleanPipeLineManagerService;
import com.deyuanyun.pic.settings.domain.base.Attachment;
import com.deyuanyun.pic.settings.domain.pipe.PipeLine;
import com.deyuanyun.pic.settings.mapper.base.AttachmentMapper;
import com.deyuanyun.pic.settings.mapper.pipe.PipeLineMapper;
import com.deyuanyun.pic.settings.support.biz.CodeUtil;

@Service
public class CleanPipeLineManagerServiceImpl implements CleanPipeLineManagerService {
	// 删除标记,1:已删除
	private static final short deleteFlag = 1;
	// 未删除
	private static final short unDeleteFlag = 0;
	// 未发布状态
	private static final short statusFlag1 = 1;
	// 已发布状态
	private static final short statusFlag2 = 2;
	// 清管类型
	private static final String CT = "漏磁检测,超声波检测,几何检测";

	private static final short version = 0;

	@Resource
	private PigTaskMapper pigTaskMapper;
	@Resource
	private PigTaskPointMapper pigTaskPointMapper;
	@Resource
	private PipeLineMapper pipeLineMapper;
	@Resource
	private AttachmentMapper attachmentMapper;
	@Resource
	private PipeLocationService pipeLocationService;

	@Override
	public PigTaskVO selectByPrimaryKey(String taskId){

		return  pigTaskMapper.selectByPrimaryKey(taskId);
	}

	@Override
	public List<PigTaskVO> getCleanPipeLineManagerIndex(QueryListVO taskVo) {
		//查询未发布和已发布的清管任务
		taskVo.setStaus(new Integer[]{1,2});
		return pigTaskMapper.queryPigTask(taskVo);
	}

	@Override
	public int deleteTaskById(String[] idsArr) throws Exception {

		int delCount = 0;
		StringBuffer sb = new StringBuffer();
		for (String id : idsArr) {
			PigTaskVO task = pigTaskMapper.selectByPrimaryKey(id);
			if(null != task){
				if(task.getStaus().equals(statusFlag1)){
					task.setDeleted(deleteFlag);
					//修改时间，用户，备注
					DomainInitUtil.initUpdateDomain(task,"删除未发布的清管任务");
					pigTaskMapper.updateByPrimaryKeySelective(task);
					//删除任务附件
					attachmentMapper.updateByBusinessId(task.getId());
					delCount++;
				}
				if(task.getStaus().equals(statusFlag2)){
					sb.append(task.getTaskName()).append(" , ");
				}
			}
		}
		return delCount;
	}

	@Override
	public int publishPigTaskById(String[] idsArr) throws Exception {
		int count = 0;

		for (String id : idsArr) {
			PigTaskVO task = pigTaskMapper.selectByPrimaryKey(id);
			if (task != null) {
				if (task.getStaus().equals(statusFlag1)) {
					task.setStaus(statusFlag2);
					//修改时间，用户，备注
					DomainInitUtil.initUpdateDomain(task);
					pigTaskMapper.updateByPrimaryKeySelective(task);
					count++;
				}
			}
		}
		return count;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Map<String, Object> queryPig(Map<String, Object> map,QueryListVO taskVo) {
//		if(StringUtils.isNotNullEmpty(taskVo.getTaskId())){//修改任务
//			PigTaskVO task = this.getTask(taskVo.getTaskId());
//			taskVo.setFromValId(task.getFromPipeValveroomId());
//			taskVo.setToValId(task.getToPipeValveroomId());
//			taskVo.setReverse(task.getIsAdverseCurrent());
//		}
		// 根据场站阀室ID获取收发球筒信息
		Map fromPig = null;
		Map toPig = null;

		if( StringUtils.isNotNullEmpty(taskVo.getFromValId())){
			fromPig =pigTaskMapper.queryPigByValRoomId(taskVo.getLineId(),taskVo.getFromValId());
		}
		if(StringUtils.isNotNullEmpty(taskVo.getToValId())){
			toPig = pigTaskMapper.queryPigByValRoomId(taskVo.getLineId(),taskVo.getToValId());
		}
		//判断收发球是否易位（默认未易位）
		if(null != fromPig && null != toPig && taskVo.getReverse().equals("0")){
			map.put("fromPig", fromPig);
			map.put("toPig", toPig);
		}else if(null != fromPig && null != toPig && taskVo.getReverse().equals("1")){
			map.put("fromPig", toPig);
			map.put("toPig", fromPig);
		}else if(null == fromPig || null == toPig){
			map.put("fromPig", null);
			map.put("toPig", null);
		}

		return map;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Map<String, Object> queryPigAndPoint(Map<String, Object> map,QueryListVO taskVo) {
		Asserts.assertTrue(StringUtils.isNotNullEmpty(taskVo.getLineId()),"未选中管道！");
		//得到起止位置对应的收发球信息
		this.queryPig(map,taskVo);


		//得到起止位置对应距离区间的mark点以及该任务的跟踪点通过记录
		//根据起止位置绝对距离得到mark点(已考虑是否易位)
		List<TrackPointVO> list = new ArrayList<TrackPointVO>();
		if(null != map.get("fromPig") && null != map.get("toPig") ){
			list = pigTaskMapper.getMarkPoint(taskVo);
		}
		map.put("markPoint", list);

		//修改任务时 得到该任务已选择mark点(对应的跟踪点通过记录)
		List<PigTaskPointVO> taskPoint = null;
		if(StringUtils.isNotNullEmpty(taskVo.getTaskId())){
			// 该任务对应的跟踪点通过记录
			QueryTaskPointVO queryP =new QueryTaskPointVO();
			queryP.setTaskId(taskVo.getTaskId());
			queryP.setReverse(taskVo.getReverse());
			taskPoint = pigTaskMapper.queryTaskPointRecord(queryP);
		}
		map.put("taskPoint",taskPoint);

		return map;
	}

	@Override
	public int saveTask( PigTaskVO taskVo, String[] points,String attId) throws Exception {
		int sucessNum = 0;//受影响条数
		Map<String, Object> praM = new HashMap<String, Object>();
		praM.put("taskName", taskVo.getTaskName());
		praM.put("taskId", taskVo.getId());
		PigTaskVO pt = pigTaskMapper.getPigTaskByName(praM);
		if (null != pt &&  taskVo.getTaskName().equals(pt.getTaskName())) {
			//用户名重复返回为-1
			return -1;
		} else if (null == taskVo.getId() || "".equals(taskVo.getId())) {
			String type = StringUtils.isEmpty(CodeUtil.getName(taskVo.getPagType())) ? "" : CodeUtil.getName(taskVo.getPagType());
			if (CT.contains(type)) {
				//下拉
				taskVo.setDetectorType(taskVo.getPagTool());
			} else {
				//输入框
				taskVo.setPigType(taskVo.getPagTool());
			}
			taskVo.setStaus(statusFlag1);
			//创建id、时间、用户
			DomainInitUtil.initCreateDomain(taskVo);
			//逻辑删除字段
			taskVo.setDeleted(unDeleteFlag);
			//保存任务
			sucessNum = pigTaskMapper.insertSelective(taskVo);
            //创建清管任务跟踪点通过记录
			for (String pointId : points) {
				PigTaskPointVO tp = new PigTaskPointVO();
				//创建id、时间、用户
				DomainInitUtil.initCreateDomain(tp);
				//逻辑删除字段
				tp.setDeleted(unDeleteFlag);
				tp.setTrackPointId(pointId);
				tp.setPiggngTaskId(taskVo.getId());
				pigTaskPointMapper.insertSelective(tp);
			}
			// 发球记录表中插入数据【任务】
			Map<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("id", UUID.randomUUID().toString().replace("-", ""));
			sendMap.put("taskId", taskVo.getId());
			sendMap.put("mark", 0);
			pigTaskMapper.insertBall(sendMap);
			// 收球记录表中插入数据【任务】
			Map<String, Object> backMap = new HashMap<String, Object>();
			backMap.put("id", UUID.randomUUID().toString().replace("-", ""));
			backMap.put("taskId", taskVo.getId());
			backMap.put("mark", 1);
			pigTaskMapper.insertBall(backMap);

		} else {//修改任务
			String type0 = StringUtils.isEmpty(CodeUtil.getName(taskVo.getPagType())) ? "" : CodeUtil.getName(taskVo.getPagType());
			if (CT.contains(type0)) {
				taskVo.setDetectorType(taskVo.getPagTool());
				taskVo.setPigType("");
			} else {
				taskVo.setPigType(taskVo.getPagTool());
				taskVo.setDetectorType("");
			}
			//只有未发布的清管任务才可以修改
			taskVo.setStaus(statusFlag1);
			DomainInitUtil.initUpdateDomain(taskVo);
			sucessNum = pigTaskMapper.updateByPrimaryKeySelective(taskVo);
			// 查询该任务对应的跟踪点通过记录
			QueryTaskPointVO queryP =new QueryTaskPointVO();
			queryP.setTaskId(taskVo.getId());
			queryP.setReverse(taskVo.getIsAdverseCurrent());
			List<PigTaskPointVO> tpList = pigTaskMapper.queryTaskPointRecord(queryP);
			if (tpList.size() > 0) {
				for (PigTaskPointVO taskPoint : tpList) {
					PigTaskPointVO tp = pigTaskPointMapper.selectByPrimaryKey(taskPoint.getId());
					// 删除跟踪点
					tp.setDeleted(deleteFlag);
					DomainInitUtil.initUpdateDomain(tp,"修改清管任务时删除原有对应跟踪点");
					pigTaskPointMapper.updateByPrimaryKeySelective(tp);
				}
			}
			// 重新创建跟踪点
			for (String pointId : points) {
				PigTaskPointVO tp = new PigTaskPointVO();
				tp.setPiggngTaskId(taskVo.getId());
				tp.setTrackPointId(pointId);
				tp.setDeleted(unDeleteFlag);
				DomainInitUtil.initCreateDomain(tp);
				pigTaskPointMapper.insertSelective(tp);
			}
			/*// 更新发球记录表
			Map<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("taskId", taskVo.getId());
			sendMap.put("lineId", taskVo.getPipeLineId());
			sendMap.put("mark", 0);
			pigTaskMapper.updateBall(sendMap);
			// 更新收球记录表
			Map<String, Object> backMap = new HashMap<String, Object>();
			backMap.put("taskId", taskVo.getId());
			backMap.put("lineId", taskVo.getPipeLineId());
			backMap.put("mark", 1);
			pigTaskMapper.updateBall(backMap);*/

		}

		if(taskVo.getId() != null && attId != null){
			attachmentMapper.updateBusinessIdById(taskVo.getId() , attId);
		}
		return sucessNum;
	}

	@Override
	public Map<String, Object> queryCleanTool(String name) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ct[] = CT.split(",");
		boolean isDropDown = false;
		for (int i = 0; i < ct.length; i++) {
			if (name.equals(ct[i])) {
				List ls = pigTaskMapper.getCleanTool();
				if (ls.size() > 0) {
					map.put("cleanTool", ls);
					isDropDown = true;
				}
			}
		}
		map.put("isDropDown", isDropDown);
		return map;
	}

	public Map<String, Object> modifyTask(Map<String, Object> map,String taskId){
		QueryListVO queryVo =new QueryListVO();
		queryVo.setTaskId(taskId);
		List<PigTaskVO> taskList = pigTaskMapper.queryPigTask(queryVo);
		PigTaskVO task = null;
		//附件
		Attachment att = null;
		if(taskList != null && taskList.size()>0){
		    task = taskList.get(0);
			//附件
			AttachmentExample example = new AttachmentExample();
			example.createCriteria().andBusinessIdEqualTo(task.getId()).andCustomTypeEqualTo("piggingTaskAtt").andDeletedEqualTo((short)0);
			List<Attachment> attList = attachmentMapper.selectByExample(example);
			if(attList != null && attList.size()>0){
				att = attList.get(0);
			}

		}
		map.put("pigTask",task);
		map.put("taskAtt", att);
		return map;
	};

	@Override
	public PigTaskVO getTask(String taskId) {
		PigTaskVO ts = pigTaskMapper.selectByPrimaryKey(taskId);
		return ts;
	}

	@Override
	public Map<String, Object> copyTask(String taskId) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		PigTaskVO pt = pigTaskMapper.selectByPrimaryKey(taskId);
		map.put("task", pt);
		boolean f = pt.getIsDropDown();
		//管道
		PipeLine pl = pipeLineMapper.selectByPrimaryKey(pt.getPipeLineId());
		map.put("pipeLine", pl);

		//根据场站阀室ID查出起止位置信息
		//起始点位置信息
		PipeLocationDTO fromVal = pipeLocationService.queryPipeLocationById(pt.getPipeLineId(),pt.getFromPipeValveroomId());
		map.put("fromVal", fromVal);
		//终止点位置信息
		PipeLocationDTO toVal = pipeLocationService.queryPipeLocationById(pt.getPipeLineId(),pt.getToPipeValveroomId());
		map.put("toVal", toVal);

		// 根据任务ID获取收发球筒信息
		if(pt.getIsAdverseCurrent().equals("0")){
			map.put("fromPig", fromVal);
			map.put("toPig", toVal);
		}else{
			map.put("fromPig", toVal);
			map.put("toPig", fromVal);
		}

		// 清管类型
		String pagType = CodeUtil.getName(pt.getPagType());
		map.put("pagType", pagType);

		// 该任务的清管工具
		String taskTool = "";
		String taskToolId = "";

		// 所有清管工具
		List ls = null;

		if(f){
			taskToolId = pt.getDetectorType();
			taskTool = CodeUtil.getName(taskToolId);
			ls = pigTaskMapper.getCleanTool();

		}else{
			taskTool = pt.getPigType();
		}
		map.put("taskTool", taskTool);
		map.put("taskToolId", taskToolId);
		map.put("cleanTool", ls);


		return map;
	}

	@Override
	public Map<String, Object> copySave(PigTaskVO taskVo) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> praM = new HashMap<String, Object>();
		praM.put("taskName", taskVo.getTaskName());
		praM.put("taskId",null);
		// 任务名称验证
		PigTaskVO pt = pigTaskMapper.getPigTaskByName(praM);
		if (null != pt && taskVo.getTaskName().equals(pt.getTaskName())) {
			map.put("msgCode", "fail_taskName");
		} else {
			// 复制任务
			PigTaskVO task = pigTaskMapper.selectByPrimaryKey(taskVo.getId());
			PigTaskVO copyTask = new PigTaskVO();
			//创建id、时间、用户
			DomainInitUtil.initCreateDomain(copyTask);
			//逻辑删除字段
			copyTask.setDeleted(unDeleteFlag);
			copyTask.setCreateRemark(taskVo.getCreateRemark());
			copyTask.setTaskName(taskVo.getTaskName());
			copyTask.setPlanPagDateTime(taskVo.getPlanPagDateTime());
            if(task.getIsDropDown()){
				copyTask.setDetectorType(taskVo.getPagTool());
			}else{
				copyTask.setPigType(taskVo.getPagTool());
			}
			copyTask.setStaus(statusFlag1);
			copyTask.setPipeLineId(task.getPipeLineId());
			copyTask.setFromPipeValveroomId(task.getFromPipeValveroomId());
			copyTask.setToPipeValveroomId(task.getToPipeValveroomId());
			copyTask.setFromPigId(task.getFromPigId());
			copyTask.setToPigId(task.getToPigId());
            copyTask.setFromMileage(task.getFromMileage());
			copyTask.setToMileage(task.getToMileage());
			copyTask.setIsAdverseCurrent(task.getIsAdverseCurrent());
			copyTask.setPagType(task.getPagType());
			copyTask.setIsDropDown(task.getIsDropDown());
			//保存复制任务
			pigTaskMapper.insertSelective(copyTask);
			// 复制跟踪点
			QueryTaskPointVO queryP =new QueryTaskPointVO();
			queryP.setTaskId(task.getId());
			queryP.setReverse(task.getIsAdverseCurrent());
			List<PigTaskPointVO> list = pigTaskMapper.queryTaskPointRecord(queryP);
			for (PigTaskPointVO pigTaskPoint : list) {
				PigTaskPointVO newP = new PigTaskPointVO();
				//创建id、时间、用户
				DomainInitUtil.initCreateDomain(newP);
				//逻辑删除字段
				newP.setDeleted(unDeleteFlag);
				newP.setPiggngTaskId(copyTask.getId());
				newP.setTrackPointId(pigTaskPoint.getTrackPointId());
				pigTaskPointMapper.insertSelective(newP);
			}

			// 发球记录表中插入数据
			Map<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("id", UUID.randomUUID().toString().replace("-", ""));
			sendMap.put("taskId", copyTask.getId());
			sendMap.put("mark", 0);
			pigTaskMapper.insertBall(sendMap);
			// 收球记录表中插入数据
			Map<String, Object> backMap = new HashMap<String, Object>();
			backMap.put("id", UUID.randomUUID().toString().replace("-", ""));
			backMap.put("taskId", copyTask.getId());
			backMap.put("mark", 1);
			pigTaskMapper.insertBall(backMap);

			//任务附件
			AttachmentExample example = new AttachmentExample();
			example.createCriteria().andBusinessIdEqualTo(task.getId()).andCustomTypeEqualTo("piggingTaskAtt").andDeletedEqualTo((short)0);
			List<Attachment> attList = attachmentMapper.selectByExample(example);
			if(attList.size() > 0){
				for (Attachment attachment : attList) {
					Attachment at = new Attachment();
					//创建id、时间、用户
					at.setPath(attachment.getPath());
					at.setRealName(attachment.getRealName());
					at.setBusinessId(copyTask.getId());
					at.setFileType(attachment.getFileType());
					at.setSource(attachment.getSource());
					at.setDeleted(unDeleteFlag);
					attachmentMapper.insertSelective(at);
				}
			}
			map.put("msgCode", "success");
		}
		return map;
	}

	/*@Override
	public List<Attachment> selectAttachmentByTaskId(String taskId) {
		return pigTaskMapper.selectAttachmentByTaskId(taskId);
	}

	@Override
	public void savefile(String sourceName, String targetName ,String tid) throws Exception{
		List<Attachment> attList = pigTaskMapper.selectAttachmentByTaskId(tid);
		if(attList.size() > 0){
			for (Attachment at : attList) {
				Attachment ach = attachmentMapper.selectByPrimaryKey(at.getId());
				ach.setDeleted(deleteFlag);
				attachmentMapper.updateByPrimaryKeySelective(ach);
			}
		}

		Attachment ach = new Attachment();
		String attaid = UUID.randomUUID().toString().replace("-", "");
		ach.setId(attaid);
		ach.setBusinessId(tid);
		ach.setDeleted(unDeleteFlag);
		ach.setVersion(version);
		ach.setBusinessId(tid);
		ach.setFileType("OTHER");
		ach.setRealName(sourceName);
		ach.setPath(targetName);
		ach.setSource("PIC_PIG_TASK");
		attachmentMapper.insertSelective(ach);
		return ;
	}*/

	/**
	 * 根据Id得到跟踪点信息
	 * @param id
	 * @return
	 */
	public TrackPointVO queryTrackPointById(String id){

		return pigTaskMapper.queryTrackPointById(id);
	}

	public  List<Map<String,Object>> querySegmentByLineId(Map<String,Object> map){

		return pigTaskMapper.querySegmentByLineId(map);
	}

}
